package com.lmaye.utils;

import com.lmaye.common.ErrorInfo;
import com.lmaye.exceptions.CommonException;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

/**
 * -- 读取配置文件
 *
 * @author lmay.Zhou
 * @qq 379839355
 * @email lmay@lmaye.com
 * @since 2019/6/9 9:40 星期日
 */
public class ReadAppConfig {
    /**
     * 读取yaml配置文件
     *
     * @param fileName 文件名称
     * @return Map<String, Object>
     */
    public Map<String, Object> readYaml(String fileName) {
        Yaml yaml = new Yaml();
        InputStream in = null;
        Map<String, Object> obj;
        try {
            in = this.getClass().getClassLoader().getResourceAsStream(fileName);
            obj = yaml.load(in);
        } catch (Exception e) {
            throw new CommonException(ErrorInfo.error("Yaml文件加载异常"), e);
        } finally {
            if(Objects.nonNull(in)) {
                try {
                    in.close();
                } catch (IOException e) {
                    throw new CommonException(ErrorInfo.error("IO流关闭异常"), e);
                }
            }
        }
        return obj;
    }

    /**
     * 读取properties配置文件
     *
     * @param fileName 文件名称
     * @return Properties
     */
    public Properties readProperties(String fileName) {
        Properties properties = new Properties();
        InputStream in = null;
        try {
            in = this.getClass().getClassLoader().getResourceAsStream(fileName);
            properties.load(in);
        } catch (IOException e) {
            throw new CommonException(ErrorInfo.error("Properties文件加载异常"), e);
        } finally {
            if(Objects.nonNull(in)) {
                try {
                    in.close();
                } catch (IOException e) {
                    throw new CommonException(ErrorInfo.error("IO流关闭异常"), e);
                }
            }
        }
        return properties;
    }
}
